package com.atguigu.gulimall.product.exception;

import com.atguigu.gulimall.common.exception.BizCodeEnume;
import com.atguigu.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一处理异常
 */
@Slf4j
@RestController
//组件
@ControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    //数据校验的异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        Map<String, String> errMap = new HashMap<>();
        log.error("数据校验出现问题{}，异常类型：{}", e.getMessage(), e.getClass());
        e.getBindingResult().getAllErrors().stream().forEach(item -> {
            String defaultMessage = item.getDefaultMessage();
            String objectName = item.getObjectName();
            errMap.put(defaultMessage, objectName);
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data", errMap);
    }

    //如果不能精确匹配异常
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        log.info("错误：", throwable);
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }

}
